import app from '@system.app';
import router from '@system.router';
import {getApp} from '../../common.js';

export default {
    data: {
        discoverAp: '',
        discoverPresent: '',
        netStatus: [],
        apExistFlag: false, //check whether AP are detected
        apSsid: ''
    },
    onInit: function () {
        this.discoverAp = this.$t('strings.page-softap-scanning-devices');
        this.discoverPresent = this.$t('strings.page-softap-present-0');
        this.netStatus = [
            {
                progress: this.$t('strings.page-softap-present-20'),
                desc: this.$t('strings.page-softap-desc-20')
            },
            {
                progress: this.$t('strings.page-softap-present-60'),
                desc: this.$t('strings.page-softap-desc-60')
            },
            {
                progress: this.$t('strings.page-softap-present-100'),
                desc: this.$t('strings.page-softap-desc-100')
            },
            {
                progress: this.$t('strings.page-softap-present-100'),
                desc: this.$t('strings.page-softap-config-fail')
            }
        ];
        this.discoverDeviceBySoftAp();
    },
    discoverDeviceBySoftAp: function () {
        getApp(this).NetConfig.discoveryBySoftAp((result) => {
            if (result.code == 0) {
                let softApInfoList = result.data;
                for (let i = 0; i < softApInfoList.length; i++) {
                    let softApInfo = softApInfoList[i];
                    let ssid = softApInfo.ssid.trim();
                    //todo Hi-xxx-Switchs: device name, vendor-defined
                    if (ssid.search('Hi-xxx-Switchs') != -1) { //Hi-xxx-Switchs
                        this.apExistFlag = true;
                        this.updateProgress(this.netStatus[0]);
                        this.connectDevice(ssid);
                        break;
                    }
                }
                if (!this.apExistFlag) { //no device is detected
                    this.updateProgress(this.netStatus[3]);
                    this.disconnectDevice();
                    this.goToFail();
                }
            } else {
                this.updateProgress(this.netStatus[3]);
                this.disconnectDevice();
                this.goToFail();
            }
        });
    },
//softap connect device
    connectDevice: function (targetDeviceId) {
        //todo request parameters
        let connectInfo = {
            targetDeviceId: targetDeviceId,
            type: 1,
            pin: '11111111',
            password: '',
            sessionId: getApp(this).NfcInfo.sessionId
        };
        getApp(this).NetConfig.connectDevice(connectInfo, (result) => {
            if (result.code == 0) {
                let jsonData = JSON.parse(result.data);
                let vendorData = jsonData.vendorData;
                getApp(this).ConfigParams.vendorData = vendorData;
                //todo the returned productId and SN depend on the service requirements of the vendor
                this.updateProgress(this.netStatus[1]);
                this.configDevice();
            } else { //connect fail
                this.updateProgress(this.netStatus[3]);
                this.disconnectDevice();
                this.goToFail();
            }
        });
    },
//softap config device
    configDevice: function () {
        let ssidPassword = '';
        if (!getApp(this).ConfigParams.wifiInfo.hasDefaultPassword) {
            ssidPassword = getApp(this).ConfigParams.wifiPwd;
        }
        if (!getApp(this).ConfigParams.wifiInfo.hasDefaultPassword && ssidPassword === '') {
            this.updateProgress(this.netStatus[3]);
            this.disconnectDevice();
            this.goToFail();
            return;
        }
        let netConfigInfo = {
            ssid: getApp(this).ConfigParams.wifiInfo.ssid,
            ssidPassword: ssidPassword,
            isDefaultPassword: getApp(this).ConfigParams.wifiInfo.hasDefaultPassword,
            channel: parseInt(getApp(this).ConfigParams.wifiInfo.channel),
            sessionId: getApp(this).NfcInfo.sessionId,
            type: 1,
            wifiApId: getApp(this).ConfigParams.wifiInfo.wifiApId,
            vendorData: 'ABcwYDVeJEMKTAYHDikzRg=='
        };
        getApp(this).NetConfig.configDeviceNet('', '', netConfigInfo, () => {
        });
        this.goToControl();
        this.disconnectDevice();
    },
//disconnect device，this method is invoked when the configuration fails
    disconnectDevice: async function() {
        let commonInfo = {
            sessionId: getApp(this).ConfigParams.deviceInfo.sessionId
        };
        await getApp(this).NetConfig.disconnectDevice(commonInfo, () => {
        });
    },
    goToFail: function () {
        router.push({
            uri: 'pages/fail/fail'
        });
    },
    goToControl: function () {
        let target = {
            bundleName: 'com.example.myapplication',
            abilityName: 'com.example.myapplication.ControlMainAbility',
            data: {
                sessionId: getApp(this).ConfigParams.deviceInfo.sessionId
            }
        }
        FeatureAbility.startAbility(target);
        app.terminate()
    },
    softCancelClick: function () {
        app.terminate();
    },
    updateProgress: function (netStatus) {
        this.discoverPresent = netStatus.progress;
        this.discoverAp = netStatus.desc;
    }
};
